package com.smallrig.extension.ext;

import com.smallrig.extension.ExtensionSpi;
import com.smallrig.extension.anno.Extension;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;


public class ExtensionBootstrap implements ApplicationContextAware {

    @Resource
    private ExtensionRegister extensionRegister;

    private ApplicationContext applicationContext;

    private List<ExtensionSpi> extensionSpiList;
    public ExtensionBootstrap(ObjectProvider<List<ExtensionSpi>> provider){
        this.extensionSpiList = provider.getIfAvailable();
    }
    @PostConstruct
    public void init(){
//        Map<String, Object> extensionBeans = applicationContext.getBeansWithAnnotation(Extension.class);
//        extensionBeans.values().forEach(
//                extension -> extensionRegister.doRegistration((ExtensionSpi) extension)
//        );
        if(CollectionUtils.isEmpty(extensionSpiList)){
            return;
        }
        for (ExtensionSpi extensionSpi : extensionSpiList) {
            extensionRegister.doRegistration(extensionSpi);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
